from rest_framework import serializers
# 导入商品sku模型
from goods.models import SKU


class CartSerizlizer(serializers.Serializer):
    """购物车序列化器"""
    # 请求参数： JSON 或 表单
    # 参数 类型 是否必须 说明
    # sku_id  int  是 商品sku
    # id  count  int   是 数量
    # selected  bool  否  是否勾选，默认勾选

    # 声明字段，校验
    sku_id = serializers.IntegerField(label="商品sku", min_value=1)
    id = serializers.IntegerField(label="数量", min_value=1)
    selected = serializers.BooleanField(label="默认勾选", default=True)

    # 校验方法
    # 校验商品id是否存在或者上架
    def validate(self, attrs):
        try:
            sku = SKU.objects.get(id=attrs["sku_id"])
        except SKU.DoesNotExist:
            raise serializers.ValidationError("商品出错")

        return attrs


class CarSKUtSerizlizer(serializers.ModelSerializer):
    """
    購物車商品序列器
    """
    count = serializers.IntegerField(label="數量")
    selected = serializers.BooleanField(label="是否勾選")

    class Meta:
        model = SKU

        fields = ('id', 'count', 'name', 'default_image_url', 'price', 'selected')


class CartDeleteSerializer(serializers.Serializer):
    """
    刪除購物車
    """
    sku_id = serializers.IntegerField(label="商品id", min_value=1)

    def validate_sku_id(self, value):

        try:
            sku = SKU.objects.get(id=value)

        except SKU.DoesNotExist:

            raise serializers.ValidationError("商品不存在")

        return value


class CartSelectedSerializer(serializers.Serializer):
    """購物車勾選全部商品"""
    selected = serializers.BooleanField(label="全選")
